package com.vanysoft.business.base.user.controller;

import com.vanysoft.business.base.org.controller.demo.OrgDemo;
import com.vanysoft.business.base.org.entity.TBaseOrg;
import com.vanysoft.business.base.org.service.BaseOrgService;
import com.vanysoft.business.base.tag.controller.demo.UserExport;
import com.vanysoft.business.base.tag.service.BaseTagService;
import com.vanysoft.business.base.team.service.BaseTeamService;
import com.vanysoft.business.base.user.controller.demo.BaseUserDemo;
import com.vanysoft.business.base.user.controller.demo.ExcelOrgUserDemo;
import com.vanysoft.business.base.user.controller.demo.ExcelUserDemo;
import com.vanysoft.business.base.user.service.BaseUserService;
import com.vanysoft.business.sys.entity.UserInfo;
import com.vanysoft.common.utils.Excel.ExcelUtil;
import com.vanysoft.common.utils.string.StringUtil;
import com.vanysoft.framework.aop.VanySoftValidation;
import com.vanysoft.framework.aop.VanySoftValidationException;
import com.vanysoft.framework.base.action.BaseController;
import com.vanysoft.framework.config.mvc.SessionUser;
import com.vanysoft.framework.constants.DbConstants;
import com.vanysoft.framework.exception.VanySoftBaseException;
import com.vanysoft.framework.messagesource.MessageCodeConstant;
import com.vanysoft.framework.utils.JSONResponse;
import com.vanysoft.framework.validation.VanySoftValidationErr;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目名称：SharpClaw移动门户
 * 类名称：UserController
 * 类描述：人员管理
 * 创建人：SharpClaw_x
 * 创建时间：2017年5月19日 上午11:55:59
 * 修改人：SharpClaw_x
 * 修改时间：2017年5月19日 上午11:55:59
 * 版本信息：@version 1.0
 * Copyright (c) 2017SharpClaw-版权所有
 * 修改备注：
 */
@RestController
@RequestMapping("/base/user")
public class BaseUserController extends BaseController {
    @Autowired
    private BaseUserService baseUserService;

    @Autowired
    private BaseOrgService orgService;

    @Autowired
    private BaseTeamService teamService;

    @Autowired
    private BaseTagService tagService;

    /**
     * Function Name               add
     *
     * @param request
     * @param baseUserDemo
     * @return
     * @throws VanySoftBaseException
     * @description 添加人员
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月8日 上午11:58:34           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/add", method = {RequestMethod.POST})
    @VanySoftValidation
    public JSONResponse add(HttpServletRequest request, @Valid BaseUserDemo baseUserDemo, BindingResult result) throws VanySoftBaseException {
        String orgList = request.getParameter("orgList");
        String teamList = request.getParameter("teamList");
        String tagList = request.getParameter("tagList");
        String roleList = request.getParameter("roleList");
        baseUserDemo.setIsCustomer(DbConstants.IS_NOT_AVAILABLE);
        baseUserService.addbaseUser(baseUserDemo, orgList, teamList, tagList, roleList);
        return new JSONResponse();

    }

    /**
     * Function Name               update
     *
     * @param request
     * @return
     * @throws VanySoftBaseException
     * @description 修改人员信息
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月22日 下午1:59:07           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    @VanySoftValidation
    public JSONResponse update(HttpServletRequest request, @Valid BaseUserDemo baseUserDemo, BindingResult result) throws VanySoftBaseException {
        String orgList = request.getParameter("orgList");
        String teamList = request.getParameter("teamList");
        String tagList = request.getParameter("tagList");
        String roleList = request.getParameter("roleList");
        baseUserService.updatebaseUser(baseUserDemo, orgList, teamList, tagList, roleList);
        return new JSONResponse();

    }

    /**
     * Function Name               deleteUsers
     *
     * @param request
     * @return
     * @throws VanySoftBaseException
     * @description 批量删除人员
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月22日 下午2:49:33           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/deleteUsers", method = {RequestMethod.POST})
    public JSONResponse deleteUsers(HttpServletRequest request) throws VanySoftBaseException {
        String userIdList = request.getParameter("userIdList");
        baseUserService.deletebaseUser(userIdList);
        return new JSONResponse();

    }

    /**
     * Function Name               checkUserExist
     *
     * @param request
     * @param userCode
     * @return
     * @throws VanySoftBaseException
     * @description 验证用户账号是否存在
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月23日 上午11:20:56           SharpClaw_x      Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/checkUserCode", method = RequestMethod.GET)
    public JSONResponse checkUserExist(HttpServletRequest request, String userCode) throws VanySoftBaseException {
        String rspCode = MessageCodeConstant.RTN_CODE_SUCCESS;
        if (!baseUserService.checkUsercode(userCode)) {
            rspCode = MessageCodeConstant.UserAndRoleException.RTN_CODE_USER_CODE;
        }

        return new JSONResponse(rspCode);
    }

    /**
     * Function Name               updateOrderNum
     *
     * @param request
     * @return
     * @throws VanySoftBaseException
     * @description 人员排序
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月22日 下午7:02:17           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/updateOrderNum", method = {RequestMethod.POST})
    public JSONResponse updateOrderNum(HttpServletRequest request) throws VanySoftBaseException {
        String userId = request.getParameter("userId");
        String orgCode = request.getParameter("orgCode");
        String action = request.getParameter("action");
        baseUserService.updateOrderNumBaseUser(orgCode, userId, action);
        return new JSONResponse();

    }

    /**
     * Function Name               resetUserPassword
     *
     * @param request
     * @return
     * @throws VanySoftBaseException
     * @description 重置密码
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月22日 下午8:02:19           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/resetUserPassword", method = {RequestMethod.POST})
    public JSONResponse resetUserPassword(@SessionUser UserInfo userInfo, HttpServletRequest request) throws VanySoftBaseException {
        String userId = request.getParameter("userId");
        String adminPassword = request.getParameter("password");
        Map<String, String> resultDate = baseUserService.resetUserPasswordBaseUser(userId, userInfo.getId(), adminPassword);
//		Map<String, String> resultDate = new HashMap<>();
//		resultDate.put("userCode", userCode);
//		resultDate.put("userPassword", newPwd);
        return new JSONResponse(resultDate);

    }

    /**
     * Function Name               resetUserStatus
     *
     * @param request
     * @return
     * @throws VanySoftBaseException
     * @description 人员禁用或启用
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月23日 上午10:21:28           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/resetUserStatus", method = {RequestMethod.POST})
    public JSONResponse resetUserStatus(HttpServletRequest request) throws VanySoftBaseException {
        String userId = request.getParameter("userId");
        String status = request.getParameter("status");
        baseUserService.resetUserStatus(userId, status);
        return new JSONResponse();

    }

    /**
     * Function Name               moveUsers
     *
     * @param request
     * @return
     * @throws VanySoftBaseException
     * @description 人员移动
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年5月23日 下午1:53:12           SharpClaw_x                    Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/moveUsers", method = {RequestMethod.POST})
    public JSONResponse moveUsers(HttpServletRequest request) throws VanySoftBaseException {
        String userIdList = request.getParameter("userIdList");
        //String orgUserIdList=request.getParameter("orgUserIdList");
        String orgCodeList = request.getParameter("orgCodeList");
        baseUserService.moveUsers(userIdList, orgCodeList);
        return new JSONResponse();

    }

//	/**
//	 * Function Name               queryOrgInfoByUserCode                                   
//	 * @param request
//	 * @return
//	 * @throws VanySoftBaseException          		             
//	 * @description 根据用户代码查询组织机构信息
//	 * Modify History:              Date             Programmer       Notes
//	 *                            ---------        ---------------  ---------
//	 *                      2017年6月2日 上午10:11:10          SharpClaw_x                     Initial
//	 **********************************************************************
//	 */
//	@RequestMapping(value="/queryOrgInfoByUserCode",method = {RequestMethod.GET})
//	public JSONResponse  queryOrgInfoByUserCode(HttpServletRequest request) throws VanySoftBaseException {
//		RedisUserInfo baseUserInfo = getLoginUser(request);
//		List<Map> listMap = baseUserService.queryOrgInfoByUserCode(baseUserInfo.getUserId());
//		return new JSONResponse(listMap);
//		
//	}
//
//	/**
//	 * Function Name               loadRoleByUserCode                                   
//	 * @param request
//	 * @return
//	 * @throws VanySoftBaseException          		             
//	 * @description 根据用户代码查询已分配角色和未分配角色信息
//	 * Modify History:              Date             Programmer       Notes
//	 *                            ---------        ---------------  ---------
//	 *                      2017年6月2日 下午4:30:42          SharpClaw_x                     Initial
//	 **********************************************************************
//	 */
//	@RequestMapping(value="/loadRoleByUserCode",method = {RequestMethod.GET})
//	public JSONResponse  loadRoleByUserCode(HttpServletRequest request) throws VanySoftBaseException {
//		String checkUserCode=request.getParameter("userCode");
//		Map<String,Object> map = baseUserService.loadRoleByUserCode(checkUserCode);
//		return new JSONResponse(map);
//		
//	}
//
//	/**
//	 * Function Name               modifyUserRoleAllotAndRemove                                   
//	 * @param request
//	 * @return
//	 * @throws VanySoftBaseException          		             
//	 * @description 用户角色分配与移除
//	 * Modify History:              Date             Programmer       Notes
//	 *                            ---------        ---------------  ---------
//	 *                      2017年6月2日 下午5:13:09          SharpClaw_x                     Initial
//	 **********************************************************************
//	 */
//	@RequestMapping(value="/modifyUserRoleAllotAndRemove",method = {RequestMethod.POST})
//	public JSONResponse  modifyUserRoleAllotAndRemove(HttpServletRequest request) throws VanySoftBaseException {
//		String checkUserCode=request.getParameter("userCode");
//		String roleCodes=request.getParameter("roleCodes");
//		baseUserService.modifyUserRoleAllotAndRemove(checkUserCode,roleCodes);
//		return new JSONResponse();
//		
//	}
//	
//	/**
//	 * Function Name               loadFunctionByUserCode                                   
//	 * @param request
//	 * @return
//	 * @throws VanySoftBaseException          		             
//	 * @description 根据人员编号查询已分配功能权限和未分配功能权限
//	 * Modify History:              Date             Programmer       Notes
//	 *                            ---------        ---------------  ---------
//	 *                      2017年6月2日 下午7:09:21          SharpClaw_x                     Initial
//	 **********************************************************************
//	 */
//	@RequestMapping(value="/loadFunctionByUserCode",method = {RequestMethod.GET})
//	public JSONResponse  loadFunctionByUserCode(HttpServletRequest request) throws VanySoftBaseException {
//		RedisUserInfo baseUserInfo = getLoginUser(request);
//		String checkUserCode=request.getParameter("checkUserCode");
//		Map<String,Object> map=baseUserService.loadFunctionByUserCode(baseUserInfo.getUserId(),checkUserCode);
//		return new JSONResponse(map);
//		
//	}
//
//	/**
//	 * Function Name               modifyUserFunctionAllotAndRemove                                   
//	 * @param request
//	 * @return
//	 * @throws VanySoftBaseException          		             
//	 * @description 用户功能分配与移除
//	 * Modify History:              Date             Programmer       Notes
//	 *                            ---------        ---------------  ---------
//	 *                      2017年6月5日 上午10:59:09          SharpClaw_x                     Initial
//	 **********************************************************************
//	 */
//	@RequestMapping(value="/modifyUserFunctionAllotAndRemove",method = {RequestMethod.POST})
//	public JSONResponse  modifyUserFunctionAllotAndRemove(HttpServletRequest request) throws VanySoftBaseException {
//		String checkUserCode=request.getParameter("checkUserCode");
//		String functionCodes=request.getParameter("functionCodes");
//		baseUserService.modifyUserFunctionAllotAndRemove(checkUserCode,functionCodes);
//		return new JSONResponse();
//		
//	}
//
//	/**
//	 * Function Name               loadDataByUserCode                                   
//	 * @param request
//	 * @return
//	 * @throws VanySoftBaseException          		             
//	 * @description 根据用户查询用户已分配数据与未分配数据
//	 * Modify History:              Date             Programmer       Notes
//	 *                            ---------        ---------------  ---------
//	 *                      2017年6月5日 上午11:18:47          SharpClaw_x                     Initial
//	 **********************************************************************
//	 */
//	@RequestMapping(value="/loadDataByUserCode",method = {RequestMethod.GET})
//	public JSONResponse  loadDataByUserCode(HttpServletRequest request) throws VanySoftBaseException {
//		RedisUserInfo baseUserInfo = getLoginUser(request);
//		String checkUserCode=request.getParameter("checkUserCode");
//		Map<String,Object> map = baseUserService.loadDataByUserCode(baseUserInfo.getUserId(),checkUserCode);
//		return new JSONResponse(map);
//		
//	}
//
//	/**
//	 * Function Name               modifyUserDataAllotAndRemove                                   
//	 * @param request
//	 * @return
//	 * @throws VanySoftBaseException          		             
//	 * @description 用户数据权限分配与移除
//	 * Modify History:              Date             Programmer       Notes
//	 *                            ---------        ---------------  ---------
//	 *                      2017年6月5日 下午4:52:51          SharpClaw_x                     Initial
//	 **********************************************************************
//	 */
//	@RequestMapping(value="/modifyUserDataAllotAndRemove",method = {RequestMethod.POST})
//	public JSONResponse  modifyUserDataAllotAndRemove(HttpServletRequest request) throws VanySoftBaseException {
//		String orgCodes=request.getParameter("orgCodes");
//		String checkUserCode=request.getParameter("checkUserCode");
//		baseUserService.modifyUserDataAllotAndRemove(orgCodes,checkUserCode);
//		return new JSONResponse();
//		
//	}

    /**
     * Function Name               excelImportUser
     *
     * @param request
     * @param file
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     * @throws VanySoftBaseException
     * @description Excel导入User
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月8日 下午3:55:08           SharpClaw_x      Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public JSONResponse excelImportUser(HttpServletRequest request, MultipartFile file, String orgCode, String repeatDeal) throws InvalidFormatException, IOException, VanySoftBaseException {

        if (StringUtils.isEmpty(orgCode)) {
            throw new VanySoftBaseException(MessageCodeConstant.ExcelException.ORG_NULL_ERROR);
        }

        Workbook workbook = ExcelUtil.createByFactory(file);
        //人员数据库重复提示
        String tip1 = null;
        //excel数据重复提示
        String tip2 = null;
        if (StringUtils.equals(repeatDeal, DbConstants.USER_COVER)) {
            tip1 = "已覆盖原有数据";
            tip2 = "保存最后一条数据";
        } else {
            tip1 = "已忽略本次数据";
            tip2 = "保存第一条数据";
        }

        TBaseOrg org = orgService.queryOrg(orgCode);
        List<TBaseOrg> orgChildren = orgService.queryOrgChildren(orgCode);

        List<String> repeatErr = new ArrayList<String>();
        Sheet sheet = workbook.getSheetAt(0);
        if (sheet != null) {
            sheet.removeRow(sheet.getRow(0));//移除标题行
            sheet.removeRow(sheet.getRow(1));//移除标题行
            List<Row> rows = ExcelUtil.readExcelContent(sheet);

            String userCode = null;
            String userName = null;
            String gender = null;
            String orgCodes = null;
            String orgNames = null;
            String mobile = null;
            String email = null;
            String wechat = null;
            String identificationNo = null;
//			String jobPosition = null;
            String dept = null;
            String tel = null;

            List<OrgDemo> newOrgs = new ArrayList<OrgDemo>();
            List<String> contentVal = new ArrayList<String>();
            List<String> userCodeList = new ArrayList<String>();
            List<ExcelUserDemo> users = new ArrayList<ExcelUserDemo>();
            for (Row row : rows) {
                String result = "第" + (row.getRowNum() + 1) + "行：";

                userName = ExcelUtil.getCellValue(row.getCell(0)).trim();
                userCode = ExcelUtil.getCellValue(row.getCell(1)).trim();
                gender = ExcelUtil.getCellValue(row.getCell(2)).trim();
                wechat = ExcelUtil.getCellValue(row.getCell(3)).trim();
                identificationNo = ExcelUtil.getCellValue(row.getCell(4)).trim();
                mobile = ExcelUtil.getCellValue(row.getCell(5)).trim();
                email = ExcelUtil.getCellValue(row.getCell(6)).trim();
//				orgNames = ExcelUtil.getCellValue(row.getCell(7)).trim();
                tel = ExcelUtil.getCellValue(row.getCell(7)).trim();
                orgCodes = "";
                dept = "";
//				jobPosition = ExcelUtil.getCellValue(row.getCell(7));


                if (StringUtils.isNotEmpty(userCode)) {
                    userCodeList.add(userCode);
                }

                if (!StringUtil.checkRegex(userCode, StringUtil.codeRegex)) {
                    result += "用户账号格式错误；";
                }
//				通过repeatDeal参数判断重复时处理方法，不做重复判断
                if (false == baseUserService.checkUsercode(userCode)) {
                    repeatErr.add("用户编号：" + userCode + "重复，" + tip1);
                }

                if (!StringUtil.checkRegex(userName, StringUtil.nameRegex)) {
                    result += "用户姓名格式错误；";
                }

                //处理部门
//				if (StringUtils.isNotEmpty(orgNames)) {
//					//如果部门字段非空
//					//校验部门是否存在，如果存在就直接保存，如果不存在就创建该部门
//					String[] orgNameArr = orgNames.split(";");
//					for (String orgName : orgNameArr) {
//						TBaseOrg userOrg = null;
//						String userOrgCode = orgCode;
//						String[] nameArr = orgName.split("/");
//						int arrLenth = nameArr.length;
//						dept+= "," + nameArr[arrLenth-1];
//						for (int i = 0 ;i<arrLenth;i++ ) {
//							if (StringUtils.isNotEmpty(nameArr[i])) {
//								if (i==0 && nameArr[i].equals(org.getOrgName())) {
//									//第一个名称如果相同的情况
//									userOrgCode = orgCode;
//								}else{
//									userOrg = orgService.queryOrgFromList(nameArr[i], userOrgCode, orgChildren);
//									if (userOrg == null) {
//										TBaseOrg demo = new TBaseOrg();
//										demo.setOrgCode(UUID.randomUUID().toString());
//										demo.setOrgName(nameArr[i]);
//										demo.setParentOrgCode(userOrgCode);
//										//加入orgList,下次重复查询
//										orgChildren.add(demo);
//										
//										OrgDemo _new = new OrgDemo();
//										_new.setOrgCode(demo.getOrgCode());
//										_new.setOrgName(demo.getOrgName());
//										_new.setParentOrgCode(demo.getParentOrgCode());
//										//加入新增列表
//										newOrgs.add(_new);
//
//										userOrgCode = demo.getOrgCode();
//									}else{
//										userOrgCode = userOrg.getOrgCode();
//									}
//								}
//							}
//						}
//						orgCodes+=","+userOrgCode;
//					}
//					
//					dept = dept.substring(1);
//					orgCodes = orgCodes.substring(1);
//				}else{
                //部门字段为空就直接保存在OrgCode下
                orgCodes = orgCode;
//				}


                if (StringUtils.isNotEmpty(mobile) && !StringUtil.checkRegex(mobile, StringUtil.mobileRegex)) {
                    result += "手机号码长度过长";
                }

                if (StringUtils.isNotEmpty(email) && !StringUtil.checkRegex(email, StringUtil.emailRegex)) {
                    result += "邮件格式错误；";
                }

                if (StringUtils.isNotEmpty(wechat) && !StringUtil.checkRegex(wechat, StringUtil.wechatRegex)) {
                    result += "SesaID号长度5~20；";
                }

                if (!StringUtils.equals(result, "第" + (row.getRowNum() + 1) + "行：")) {
                    contentVal.add(result);
                }

                ExcelUserDemo user = new ExcelUserDemo();
                user.setUserCode(userCode);
                user.setUserName(userName);
                user.setGender(StringUtils.equals(gender, "男") ? "1" : "0");
                user.setOrgCodes(orgCodes);
                user.setMobile(mobile);
                user.setEmail(email);
                user.setWechat(wechat);
                user.setIdentificationNo(identificationNo);
//				user.setJobPostion(jobPosition);
                TBaseOrg userOrg = orgService.queryOrg(orgCodes);
                user.setDept(userOrg.getOrgName());
                user.setTel(tel);
                //非外部人员
                user.setIsCustomer(DbConstants.IS_NOT_AVAILABLE);

                users.add(user);
            }

            List<String> excelRepeat = StringUtil.checkListRepeat(userCodeList);
            for (String userId : excelRepeat) {
                repeatErr.add("用户编号：" + userId + "excel中重复，" + tip2);
            }


            List<VanySoftValidationErr> validationlist = new ArrayList<VanySoftValidationErr>();
            VanySoftValidationErr contentErr = null;

            if (contentVal != null && contentVal.size() > 0) {
                contentErr = new VanySoftValidationErr();
                contentErr.setField("内容校验结果");
                contentErr.setMessage(contentVal.toArray(new String[contentVal.size()]));
                validationlist.add(contentErr);
            }

            if (validationlist != null && validationlist.size() > 0) {
                throw new VanySoftValidationException(MessageCodeConstant.ExcelException.VALIDATION_RESULT, validationlist);
            } else {
                orgService.addOrgBatch(newOrgs);
                List<ExcelOrgUserDemo> orgUsers = baseUserService.addExcelUser(users, repeatDeal);
                baseUserService.addOrgUsers(orgUsers);
            }
        }

        return new JSONResponse(MessageCodeConstant.RTN_CODE_SUCCESS, repeatErr);
    }

    /**
     * Function Name               excelExportOrg
     *
     * @param request
     * @param response
     * @throws InvalidFormatException
     * @throws VanySoftBaseException
     * @description 部门人员导出
     * Modify History:              Date             Programmer       Notes
     * ---------        ---------------  ---------
     * 2017年6月12日 下午1:47:48           SharpClaw_x      Initial
     * *********************************************************************
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void excelExportOrg(HttpServletRequest request, HttpServletResponse response, String type, String searchValue) throws VanySoftBaseException {


        List<Map<String, Object>> sheetList = new ArrayList<Map<String, Object>>();
        Map<String, Object> sheet1 = new HashMap<String, Object>();

        String[] header1 = {"账号", "姓名", "性别", "部门", "手机", "邮箱", "状态"};
        String[] rowkey1 = {"userAccount", "userName", "genderStr", "dept", "mobile", "email", "statusStr"};

        UserExport orgExport = null;
        if (StringUtils.equals(type, DbConstants.ORGUSER_EXPORT)) {

            String orgCode = request.getParameter("orgCode");
            orgExport = baseUserService.queryExcelOrgUser(orgCode, searchValue);
        } else if (StringUtils.equals(type, DbConstants.TEAMUSER_EXPORT)) {

            String teamCode = request.getParameter("teamCode");
            orgExport = teamService.queryTeamExcelUsers(teamCode, searchValue);
        } else if (StringUtils.equals(type, DbConstants.TAGUSER_EXPORT)) {

            String tagCode = request.getParameter("tagCode");
            orgExport = tagService.queryExcelTagUsers(tagCode, searchValue);
        }

        String fileName = orgExport.getFileName();
        List<Map<String, Object>> userList = orgExport.getUsers();

        sheet1.put("title", fileName);
        sheet1.put("rows", userList);
        sheet1.put("rowkey", rowkey1);
        sheet1.put("header", header1);
        sheetList.add(sheet1);

        OutputStream toClient = null;
        Workbook workbook = ExcelUtil.exportExample(sheetList);
        try {


            // 清空response
            response.reset();
            // 设置response的Header
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
            response.setContentType("text/html;charset=UTF-8");
            toClient = new BufferedOutputStream(response.getOutputStream());
            workbook.write(toClient);
            toClient.flush();
        } catch (IOException ex) {
            throw new VanySoftBaseException(MessageCodeConstant.ExcelException.DOWNLOAD_FAIL);
        } finally { // close() 方法在finally模块中处理
            try {
                if (toClient != null) {
                    toClient.close();
                }
            } catch (IOException e) {
                throw new VanySoftBaseException(MessageCodeConstant.ExcelException.DOWNLOAD_FAIL);
            }
        }
    }

}
